package south

import (
	"encoding/json"
	"iot-base/common/config"
	"iot-base/common/mqtt"
	"iot-base/common/notify"
	"iot-base/common/redis"
	"iot-base/common/types"
	"strconv"
	"strings"
)

func handleRecord(client mqtt.IOTMQTTBroker, topic string, pCmd *mqtt.Cmd) {
	if pCmd != nil {
		if data, ok := pCmd.Body.(*types.ReqRecordData); ok {
			// 发布主题消息
			notify.PubMsg(false, "ReportData", data)
			var buf strings.Builder
			buf.WriteString("cloud_report.")
			buf.WriteString(data.ID)
			buf.WriteString(strconv.FormatInt(data.Seq, 10))
			buf.WriteString(".msg.list")
			resp, err := redis.BLPop(3, buf.String())
			//回复
			var replyData types.RespRecordData
			replyData.ID = data.ID
			replyData.Seq = data.Seq
			replyData.Result = data.Params
			if err != nil || len(resp) == 0 {
				replyData.Code = -1
				replyData.Msg = "time out"
				client.Reply(config.GetEdgeTopic(), pCmd, 0, ""+pCmd.SourceID, replyData)
				return
			}
			json.Unmarshal([]byte(resp[1]), &replyData)
			client.Reply(config.GetEdgeTopic(), pCmd, 0, ""+pCmd.SourceID, replyData)
			return
		}
	} else {
		client.Reply(config.GetEdgeTopic(), pCmd, -1, "not exist "+pCmd.SourceID, nil)
		return
	}
}
